package at.spengergasse.web.servlet.plz;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import at.spengergasse.dao.PlzDao;
import at.spengergasse.dao.derby.PlzDAODerbyImpl;
import at.spengergasse.web.EntryPointURLEnum;
import at.spengergasse.web.servlet.LoginServlet;

@SuppressWarnings("serial")
public abstract class AbstractPlzServlet extends LoginServlet {

  protected static PlzDao plzDAO = new PlzDAODerbyImpl();

  public AbstractPlzServlet() throws Exception {
  }

  protected Long checkPlzIdParam(HttpServletRequest req,
      HttpServletResponse resp) throws ServletException, IOException {
    Long plzId = null;
    try {
      plzId = Long.valueOf(req.getParameter(PlzFieldNames.ID));
    }
    catch (Exception e) {
      log.warn("problems with given plzId!", e);
    }

    if (plzId == null) {
      redirectToPlzList(req, resp, "wrong plzId");
      return null;
    }
    return plzId;
  }

  protected Long checkPlzParam(HttpServletRequest req,
	      HttpServletResponse resp) throws ServletException, IOException {
	    Long plzId = null;
	    try {
	      plzId = Long.valueOf(req.getParameter(PlzFieldNames.ID));
	    }
	    catch (Exception e) {
	      log.warn("problems with given plzId!", e);
	    }

	    if (plzId == null) {
	      redirectToPlzList(req, resp, "wrong plzId");
	      return null;
	    }
	    return plzId;
	  }
  
  protected String checkPlzOrtParam(HttpServletRequest req,
	      HttpServletResponse resp) throws ServletException, IOException {
	    String plzOrt = null;
	    try {
	      plzOrt = (req.getParameter(PlzFieldNames.ORT));
	    }
	    catch (Exception e) {
	      log.warn("problems with given plzOrt!", e);
	    }

	    if (plzOrt == null) {
	      redirectToPlzList(req, resp, "wrong plzOrt");
	      return null;
	    }
	    return plzOrt;
	  }
  
  protected void redirectToPlzList(HttpServletRequest req,
      HttpServletResponse resp) throws ServletException, IOException {
    redirectToPlzList(req, resp, null);
  }

  protected void redirectToPlzList(HttpServletRequest req,
      HttpServletResponse resp, String errorMessage) throws ServletException,
      IOException {
    if (errorMessage != null) {
      req.getSession(true).setAttribute("errorMessage", errorMessage);
    }
    resp.sendRedirect(EntryPointURLEnum.PLZ_LIST_ALL.getUrl());
  }  
}
